package zmee.task;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.kingdee.cosmic.ctrl.common.CtrlUtil;
import json.JSON;
import json.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDException;
import kd.bos.org.api.IOrgService;
import kd.bos.org.model.OrgDutyView;
import kd.bos.org.model.OrgParam;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.service.ServiceFactory;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.org.OrgUnitServiceHelper;
import kd.bos.servicehelper.org.OrgViewType;
import kd.fi.cas.helper.OperateServiceHelper;
import zmee.util.OARequestUtil;

import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.*;

import static kd.bos.org.utils.Consts.ROOT_ORG_ID;

/**
* @author lijiawang
* @Date 2022/11/17 17:39
* @Description:同步OA组织
*/
public class OAOrgTask extends AbstractTask {
    private Log logger = LogFactory.getLog(OAOrgTask.class);
    DynamicObject oauser = OARequestUtil.getInitialize().config("oaorg");
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        if(oauser == null){
            logger.info("===未配置相关配置===");
        }

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        Integer pageSize=1000;
        Integer orgPageIndex=1;
        JSONObject boby=new JSONObject();
        boby.put("subcompanycode","26501");
        boby.put("sourceFrom","text");
        boby.put("pageSize",pageSize);
        boby.put("timestamp",format);

        while (true) {
            boby.put("pageIndex", orgPageIndex);
            String oaUser = OARequestUtil.getOARequest(oauser, boby.toString());
            if (oaUser != null || !"".equals(oaUser)) {
                JSONObject jsonObject = JSON.parseObject(oaUser);
                Boolean status = jsonObject.getBoolean("api_status");
                logger.info("====jsonObject====:"+jsonObject);
                if (status) {
                    Integer total = jsonObject.getInteger("total");
                    String result = jsonObject.getString("result");
                    if (!StrUtil.isEmpty(result)) {
                        List<Map<String, Object>> maps = OAUserTask.transverterMap(result, "Org");
                        logger.info("=====maps==== ："+maps);
                        logger.info("=====size==== ："+maps.size());
                        parentOrg(maps, "26501");
                    }
                    if (total.equals(pageSize)) {
                        ++orgPageIndex;
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }
        }
    }


    private void parentOrg(List<Map<String,Object>> listMap ,String txt){
        logger.info("=====grpid====："+txt);
        if(!StringUtils.isNotBlank(txt)){
            return;
        }
        List <Map<String,Object>> parenList=new ArrayList<>();
        //根据上级组织ID获取组织
        for (Map<String,Object> map:listMap) {
            String parentid = map.get("parentid").toString();
            if(txt.equals(parentid)){
                parenList.add(map);
            }
        }
        logger.info("=====parenList====："+txt+parenList);
        //同步OA组织
        for (Map<String,Object> map:parenList) {
            String grpid = map.get("grpid").toString();
            DynamicObject adminorg = BusinessDataServiceHelper.loadSingle("bos_adminorg", "id,name", new QFilter[]{new QFilter("number", QCP.equals, grpid)});
           try {
               if(adminorg == null){
                   orgAdd(map,"save");
                   continue;
               }else {
                   orgAdd(map,"update");
               }
           }catch (Exception e){
               logger.info("=====组织跟新或添加失败====："+e);
           }
            parentOrg(listMap,grpid);
        }
    }

    private void orgAdd(Map map,String txt){
        /* 新增单个视图方案的组织 */
        OrgParam param = new OrgParam();
        param.setParentId(ROOT_ORG_ID);

        if(!"update".equals(txt)){
            param.setNumber(map.get("grpid").toString());//编码
        }
        param.setName(map.get("displayname").toString());//名称
        String parentid = map.get("parentid").toString();
        QFilter qFilter=new QFilter("number", QCP.equals,parentid);
        DynamicObject org = BusinessDataServiceHelper.loadSingle("bos_adminorg", "id,number", qFilter.toArray());
        param.setParentId(org.getLong("id"));
        if(parentid.equals("26501")){
            param.setOrgPatternId(1);
        }
        TreeMap<String, OrgDutyView> treeMap=new TreeMap();
        OrgDutyView dutyView = new OrgDutyView();
        dutyView.setParentId(org.getLong("id"));
        treeMap.put(OrgViewType.Admin,dutyView);
        param.setMultiViewMap(treeMap);

        Map<String,Object> propertyMap=new HashMap<>();
        propertyMap.put("oaid",map.get("id"));
        param.setPropertyMap(propertyMap);
        if("update".equals(txt)){
            OrgUnitServiceHelper.update(param);
            return;
        }
        OrgUnitServiceHelper.add(param);
    }
}
